package messagesvc.websocket.service;

import java.util.ArrayDeque;
import java.util.Queue;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WsService {

  private static final Queue<Receiver> message = new ArrayDeque<>();

  public boolean sendText(String receiver, String text){
    WsSession.getAndSend(receiver, text);
    return true;
  }

  public boolean sendByQueue(String receiver, String text){
    message.add(Receiver.builder()
        .receiver(receiver)
        .text(text)
        .build());
    doSend();
    return true;
  }

  private void doSend(){
    while (message.peek() != null){
      Receiver receiver = message.peek();
      WsSession.getAndSend(receiver.getReceiver(), receiver.getText());
    }
  }

  @Data
  @Builder
  static class Receiver {
    String receiver;
    String text;
  }
}
